package com.xiguanlezz.cn.server;

import com.xiguanlezz.cn.codec.RpcDecoder;
import com.xiguanlezz.cn.codec.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.Setter;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/3 14:32
 * @Description：
 */
public class NettyServer extends BaseServer {
    @Setter
    private Map<String, Object> handlerMap;
    @Setter
    private String reflectType; /* 调用本地方法的类型，比如：JDK反射、Cglib调用 */

    public NettyServer(InetSocketAddress address) {
        super(address);
    }

    public NettyServer(InetSocketAddress address, String reflectType) {
        super(address);
        this.reflectType = reflectType;
    }

    @Override
    public void startServer() {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            ChannelFuture channelFuture = serverBootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                            ChannelPipeline pipeline = nioSocketChannel.pipeline();
                            pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                            // 引入自定义的编解码器（自带沾包和拆包功能）
                            pipeline.addLast(new RpcDecoder());
                            pipeline.addLast(new RpcEncoder());
                            RpcProviderHandler rpcProviderHandler = new RpcProviderHandler(handlerMap);
                            if (Objects.nonNull(reflectType)) {
                                rpcProviderHandler.setReflectType(reflectType);
                            }
                            pipeline.addLast(rpcProviderHandler);
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .bind(host, port)
                    .sync();
            channelFuture.channel().closeFuture().get();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
